package com.xmartjoy.java.david;

import org.hibernate.*;
import org.hibernate.cfg.*;

public class HibernateUtil {
    private static SessionFactory sessionFactory = null;
    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private static Session session = null;


    private HibernateUtil(){}

    private static SessionFactory getSessionFactory(){
        try{
            Configuration cfg = new Configuration();
            cfg.configure();
            sessionFactory = cfg.buildSessionFactory();
        }catch (Throwable ex){
            throw new ExceptionInInitializerError(ex);
        }finally {
            return sessionFactory;
        }
    }

    public static void rebuildSessionFactory(){
        try{
            Configuration cfg = new Configuration();
            cfg.configure();
            sessionFactory = cfg.buildSessionFactory();
        }catch (Exception e){
            System.err.println("Error Creating SessionFactory!");
            e.printStackTrace();
        }
    }

    //    public static Session getSession(){
//        SessionFactory sessionFactory = getSessionFactory();
//        return sessionFactory.openSession();
//    }

    public static Session getSession() throws HibernateException{
        Session session = (Session) threadLocal.get();
        if(session == null||!session.isOpen()){
            if(sessionFactory==null)
                rebuildSessionFactory();
            session = (sessionFactory!=null)?sessionFactory.openSession():null;
            threadLocal.set(session);
        }
        return session;
    }

//    public static void closeSession(){
//        sessionFactory.close();
//    }

    public static void closeSession() throws HibernateException{
        Session session = (Session) threadLocal.get();
        //System.out.println(session.toString());
        threadLocal.set(null);
        if(session != null){
            session.close();
        }
    }
    public static void shutdown(){
        //getSessionFactory().close();
        sessionFactory.close();
    }
//    static {
//        try{
//            Configuration cfg = new Configuration();
//            cfg.configure();
//            sessionFactory = cfg.buildSessionFactory();
//        }catch (Throwable ex){
//            throw new ExceptionInInitializerError(ex);
//        }
//    }
//
//    public static SessionFactory getSessionFactory(){
//        return sessionFactory;
//    }
//
//    public static void closeSession() throws HibernateException{
//        Session session = (Session) threadLocal.get();
//        threadLocal.set(null);
//        if(session != null){
//            session.close();
//        }
//    }
//

//

}
